package com.innovation.ic.cc.base.service.cc.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.innovation.ic.cc.base.handler.cc.ErpHandler;
import com.innovation.ic.cc.base.handler.cc.InquiryPriceHandler;
import com.innovation.ic.cc.base.mapper.cc.DiscussionPriceRecordMapper;
import com.innovation.ic.cc.base.mapper.cc.InquiryPriceMapper;
import com.innovation.ic.cc.base.mapper.cc.InquiryPriceRecordMapper;
import com.innovation.ic.cc.base.mapper.cc.QuotedPriceRecordMapper;
import com.innovation.ic.cc.base.model.cc.DiscussionPriceRecord;
import com.innovation.ic.cc.base.model.cc.InquiryPrice;
import com.innovation.ic.cc.base.model.cc.InquiryPriceRecord;
import com.innovation.ic.cc.base.model.cc.QuotedPriceRecord;
import com.innovation.ic.cc.base.pojo.Request.ErpPushInquiryPriceRequest;
import com.innovation.ic.cc.base.pojo.constant.handler.RabbitMqConstants;
import com.innovation.ic.cc.base.pojo.enums.*;
import com.innovation.ic.cc.base.pojo.variable.AuthenticationUser;
import com.innovation.ic.cc.base.pojo.variable.InquiryPrice.*;
import com.innovation.ic.cc.base.pojo.variable.ServiceResult;
import com.innovation.ic.cc.base.service.ServiceHelper;
import com.innovation.ic.cc.base.service.cc.InquiryPriceService;
import com.innovation.ic.cc.base.vo.InquiryPrice.InquiryPriceDelayedVo;
import com.innovation.ic.cc.base.vo.InquiryPrice.InquiryPricePageListVo;
import com.innovation.ic.cc.base.vo.InquiryPrice.InquiryPriceVo;
import com.innovation.ic.cc.base.vo.discussionPrice.DiscussionPriceCreatedVo;
import com.rabbitmq.client.AMQP;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zengqinglong
 * @desc 询价管理
 * @Date 2023/2/14 13:59
 **/
@Slf4j
@Service
public class InquiryPriceServiceImpl extends ServiceImpl<InquiryPriceMapper, InquiryPrice> implements InquiryPriceService {
    @Resource
    private InquiryPriceRecordMapper inquiryPriceRecordMapper;

    @Resource
    private InquiryPriceHandler inquiryPriceHandler;
    @Resource
    private ErpHandler erpHandler;

    @Resource
    private ServiceHelper serviceHelper;

    @Resource
    private QuotedPriceRecordMapper quotedPriceRecordMapper;

    @Resource
    private DiscussionPriceRecordMapper discussionPriceRecordMapper;

    /**
     * 询价
     *
     * @param inquiryPriceVo
     * @param authenticationUser
     * @return
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, timeout = 30, rollbackFor = Exception.class)
    public InquiryPrice releaseInquiryPrice(InquiryPriceVo inquiryPriceVo, AuthenticationUser authenticationUser) {
        //添加询价单
        Date date = new Date();
        InquiryPrice inquiryPrice = new InquiryPrice();
        String number = inquiryPriceHandler.generateInquiryPriceNumber();
        inquiryPrice.setOddNumbers(number);
        inquiryPrice.setInquiryMethod(1);
        //todo 通过公司id 获取对应的公共信息 发票 币种 公司seitid 发货地
        inquiryPrice.setMyCompanyId(inquiryPriceVo.getMyCompanyId());
        inquiryPrice.setMyCompanyName("测试公司名称");
        inquiryPrice.setSiteId("测试公司");
        inquiryPrice.setCountryRegionId("1111");
        inquiryPrice.setCurrency(CurrencyEnum.RMB.getType());
        inquiryPrice.setInvoiceName("增值票");
        inquiryPrice.setInvoiceTypeId("111");
        inquiryPrice.setDeliveryPlace(DeliveryPlaceTypeEnum.MAINLAND.getType());


        //todo 通过当前登陆人获取，对应销售id
        inquiryPrice.setUserId(authenticationUser.getId());
        inquiryPrice.setSalerId("测试人员");
        inquiryPrice.setRealName(authenticationUser.getUsername());
        inquiryPrice.setInquiryType(inquiryPriceVo.getInquiryType());
        inquiryPrice.setDeadline(inquiryPriceVo.getDeadline());
        inquiryPrice.setStatus(InquiryPriceStatusEnum.INIT.getStatus());
        inquiryPrice.setCreateTime(date);
        inquiryPrice.setUpdateTime(date);
        baseMapper.insert(inquiryPrice);
        Integer id = inquiryPrice.getId();
        //批量解析询价记录
        List<InquiryPriceRecord> inquiryPriceRecordList = inquiryPriceVo.getInquiryPriceRecordVoList().stream().map(inquiryPriceRecordVo -> {
            InquiryPriceRecord inquiryPriceRecord = new InquiryPriceRecord();
            BeanUtils.copyProperties(inquiryPriceRecordVo, inquiryPriceRecord);
            inquiryPriceRecord.setInquiryPriceId(id);
            inquiryPriceRecord.setStatus(InquiryPriceRecordStatusEnum.PENDING.getStatus());
            inquiryPriceRecord.setDeadline(inquiryPrice.getDeadline());
            inquiryPriceRecord.setDiscussionPriceFlag(true);
            inquiryPriceRecord.setCreateTime(date);
            inquiryPriceRecord.setUpdateTime(date);
            return inquiryPriceRecord;
        }).collect(Collectors.toList());

        inquiryPriceRecordMapper.insertBatch(inquiryPriceRecordList);

        //发送询价
        pushErpInquiry(id, authenticationUser.getToken());

        return inquiryPrice;
    }

    /**
     * 获取询价单
     *
     * @param inquiryPricePageListVo
     * @return
     */
    @Override
    public PageInfo<InquiryPriceListPojo> pageList(InquiryPricePageListVo inquiryPricePageListVo, AuthenticationUser authenticationUser) {
        PageHelper.startPage(inquiryPricePageListVo.getPageNo(), inquiryPricePageListVo.getPageSize());
        if (authenticationUser.getIsMain() == 0) {
            List<String> ids = new ArrayList<>();
            if (authenticationUser.getPosition().equals("1")) {
                //todo 需要查询经理手底下有多少个员工

            } else {
                ids.add(authenticationUser.getId());
                inquiryPricePageListVo.setUserIds(ids);
            }
        }
        //转换状态
        inquiryPricePageListVo.setStatusList(compareStatus(inquiryPricePageListVo.getStatus()));

        List<InquiryPriceAndInquiryPriceRecordBO> list = baseMapper.pageList(inquiryPricePageListVo);

        List<InquiryPriceListPojo> listPojo = new ArrayList<>();
        for (InquiryPriceAndInquiryPriceRecordBO inquiryPriceAndInquiryPriceRecordBO : list) {
            InquiryPriceListPojo inquiryPriceListPojo = new InquiryPriceListPojo();
            //封装询价单详情
            InquiryPricePojo inquiryPricePojo = new InquiryPricePojo();
            BeanUtils.copyProperties(inquiryPriceAndInquiryPriceRecordBO, inquiryPricePojo);
            inquiryPricePojo.setCurrencyDesc(CurrencyEnum.parse(inquiryPriceAndInquiryPriceRecordBO.getCurrency()).getDesc());
            inquiryPricePojo.setDeliveryPlaceDesc(CurrencyEnum.parse(inquiryPriceAndInquiryPriceRecordBO.getDeliveryPlace()).getDesc());
            inquiryPricePojo.setStatusDesc(InquiryPriceStatusEnum.parse(inquiryPriceAndInquiryPriceRecordBO.getStatus()).getDesc());
            inquiryPriceListPojo.setInquiryPricePojo(inquiryPricePojo);
            //封装型号详情
            List<InquiryPriceRecordPojo> inquiryPriceRecordPojoList = new ArrayList<>();
            for (InquiryPriceRecordBO inquiryPriceRecordBO : inquiryPriceAndInquiryPriceRecordBO.getInquiryPriceRecordBOS()) {
                inquiryPriceRecordPojoList.add(parsingDataByStatus(inquiryPricePojo, inquiryPriceRecordBO));
            }
            inquiryPriceListPojo.setInquiryPriceRecordPojoList(inquiryPriceRecordPojoList);
            listPojo.add(inquiryPriceListPojo);
        }

        return new PageInfo<>(listPojo);
    }

    /**
     * 1:待询价，2:待报价，3:已报价，4:议价中，5:议价完成，6:已生成订单,7:议价失败, 8:超时未报价,9:无法报价, 10:无效报价
     * 根据状态解析数据
     */
    public InquiryPriceRecordPojo parsingDataByStatus(InquiryPricePojo inquiryPricePojo, InquiryPriceRecordBO inquiryPriceRecordBO) {
        InquiryPriceRecordPojo inquiryPriceRecordPojo = new InquiryPriceRecordPojo();
        //议价中 议价失败 显示的是议价单的信息
        if (inquiryPriceRecordBO.getRecordStatus().equals(InquiryPriceRecordStatusEnum.DISCUSSION_PRICE_IN.getStatus()) ||
                inquiryPriceRecordBO.getRecordStatus().equals(InquiryPriceRecordStatusEnum.DISCUSSION_PRICE_FAIL.getStatus())) {
            //查询报价
            LambdaQueryWrapper<QuotedPriceRecord> quotedPriceRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
            quotedPriceRecordLambdaQueryWrapper.eq(QuotedPriceRecord::getRecordId, inquiryPriceRecordBO.getInquiryPriceRecordId());
            quotedPriceRecordLambdaQueryWrapper.eq(QuotedPriceRecord::getQuotedType, 1);
            quotedPriceRecordLambdaQueryWrapper.orderByDesc(QuotedPriceRecord::getCreateTime);
            quotedPriceRecordLambdaQueryWrapper.last("limit 1");
            QuotedPriceRecord quotedPriceRecord = quotedPriceRecordMapper.selectOne(quotedPriceRecordLambdaQueryWrapper);
            if (null != quotedPriceRecord) {
                //查询议价
                LambdaQueryWrapper<DiscussionPriceRecord> discussionPriceRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
                discussionPriceRecordLambdaQueryWrapper.eq(DiscussionPriceRecord::getQuotedPriceId, quotedPriceRecord.getId());
                //查询出 议价中 议价失败的状态议价单
                discussionPriceRecordLambdaQueryWrapper.in(DiscussionPriceRecord::getStatus,
                        DiscussionPriceRecordStatusEnum.DISCUSSION_PRICE_IN.getStatus(),
                        DiscussionPriceRecordStatusEnum.DISCUSSION_PRICE_FAIL.getStatus());
                discussionPriceRecordLambdaQueryWrapper.orderByDesc(DiscussionPriceRecord::getCreateTime);
                discussionPriceRecordLambdaQueryWrapper.last("limit 1");
                DiscussionPriceRecord discussionPriceRecord = discussionPriceRecordMapper.selectOne(discussionPriceRecordLambdaQueryWrapper);
                if (null != discussionPriceRecord) {
                    BeanUtils.copyProperties(inquiryPriceRecordBO, inquiryPriceRecordPojo);
                    inquiryPriceRecordPojo.setDeadline(inquiryPriceRecordBO.getRecordDeadline());
                    inquiryPriceRecordPojo.setStatus(inquiryPriceRecordBO.getRecordStatus());
                    inquiryPriceRecordPojo.setStatusDesc(InquiryPriceRecordStatusEnum.parse(inquiryPriceRecordBO.getRecordStatus()).getDesc());
                    inquiryPriceRecordPojo.setNote(inquiryPriceRecordBO.getRecordNote());
                    inquiryPriceRecordPojo.setCreateTime(inquiryPriceRecordBO.getRecordCreateTime());
                    inquiryPriceRecordPojo.setUpdateTime(inquiryPriceRecordBO.getRecordUpdateTime());
                    inquiryPriceRecordPojo.setInquiryType(inquiryPricePojo.getInquiryType());
                    inquiryPriceRecordPojo.setInquiryTypeDesc(InquiryTypeEnum.parse(inquiryPricePojo.getInquiryType()).getDesc());
                    inquiryPriceRecordPojo.setInvoiceName(inquiryPricePojo.getInvoiceName());
                    //用议价能修改的替换询价信息 目标价 议价数量 交货日期 有效期 报价
                    inquiryPriceRecordPojo.setQuotedPrice(quotedPriceRecord.getQuotedPrice());
                    inquiryPriceRecordPojo.setAmount(discussionPriceRecord.getAmount());
                    inquiryPriceRecordPojo.setAcceptPrice(discussionPriceRecord.getAcceptPrice());
                    inquiryPriceRecordPojo.setDeliveryDate(discussionPriceRecord.getDeliveryDate());
                    inquiryPriceRecordPojo.setDeadline(discussionPriceRecord.getDeadline());
                    return inquiryPriceRecordPojo;
                }
            }
            BeanUtils.copyProperties(inquiryPriceRecordBO, inquiryPriceRecordPojo);
            inquiryPriceRecordPojo.setDeadline(inquiryPriceRecordBO.getRecordDeadline());
            inquiryPriceRecordPojo.setStatus(inquiryPriceRecordBO.getRecordStatus());
            inquiryPriceRecordPojo.setStatusDesc(InquiryPriceRecordStatusEnum.parse(inquiryPriceRecordBO.getRecordStatus()).getDesc());
            inquiryPriceRecordPojo.setNote(inquiryPriceRecordBO.getRecordNote());
            inquiryPriceRecordPojo.setCreateTime(inquiryPriceRecordBO.getRecordCreateTime());
            inquiryPriceRecordPojo.setUpdateTime(inquiryPriceRecordBO.getRecordUpdateTime());
            inquiryPriceRecordPojo.setInquiryType(inquiryPricePojo.getInquiryType());
            inquiryPriceRecordPojo.setInquiryTypeDesc(InquiryTypeEnum.parse(inquiryPricePojo.getInquiryType()).getDesc());
            inquiryPriceRecordPojo.setInvoiceName(inquiryPricePojo.getInvoiceName());
            return inquiryPriceRecordPojo;
        }

        //已生成订单 议价完成 已报价 显示的是报价信息
        if(inquiryPriceRecordBO.getRecordStatus().equals(InquiryPriceRecordStatusEnum.ORDER_GENERATED.getStatus()) ||
                inquiryPriceRecordBO.getRecordStatus().equals(InquiryPriceRecordStatusEnum.DISCUSSION_PRICE_COMPLETE.getStatus()) ||
                inquiryPriceRecordBO.getRecordStatus().equals(InquiryPriceRecordStatusEnum.QUOTED.getStatus())){
            //查询议价后的报价
            LambdaQueryWrapper<QuotedPriceRecord> quotedPriceRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
            quotedPriceRecordLambdaQueryWrapper.eq(QuotedPriceRecord::getInquiryPriceRecordId, inquiryPriceRecordBO.getInquiryPriceRecordId());
            quotedPriceRecordLambdaQueryWrapper.eq(QuotedPriceRecord::getQuotedType, 2);
            quotedPriceRecordLambdaQueryWrapper.orderByDesc(QuotedPriceRecord::getCreateTime);
            quotedPriceRecordLambdaQueryWrapper.last("limit 1");
            QuotedPriceRecord quotedPriceRecord = quotedPriceRecordMapper.selectOne(quotedPriceRecordLambdaQueryWrapper);
            if (null == quotedPriceRecord) {
                //查询询价后的报价
                LambdaQueryWrapper<QuotedPriceRecord> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(QuotedPriceRecord::getInquiryPriceRecordId, inquiryPriceRecordBO.getInquiryPriceRecordId());
                queryWrapper.eq(QuotedPriceRecord::getQuotedType, 1);
                queryWrapper.orderByDesc(QuotedPriceRecord::getCreateTime);
                queryWrapper.last("limit 1");
                quotedPriceRecord= quotedPriceRecordMapper.selectOne(quotedPriceRecordLambdaQueryWrapper);
            }

            BeanUtils.copyProperties(inquiryPriceRecordBO, inquiryPriceRecordPojo);
            inquiryPriceRecordPojo.setDeadline(inquiryPriceRecordBO.getRecordDeadline());
            inquiryPriceRecordPojo.setStatus(inquiryPriceRecordBO.getRecordStatus());
            inquiryPriceRecordPojo.setStatusDesc(InquiryPriceRecordStatusEnum.parse(inquiryPriceRecordBO.getRecordStatus()).getDesc());
            inquiryPriceRecordPojo.setNote(inquiryPriceRecordBO.getRecordNote());
            inquiryPriceRecordPojo.setCreateTime(inquiryPriceRecordBO.getRecordCreateTime());
            inquiryPriceRecordPojo.setUpdateTime(inquiryPriceRecordBO.getRecordUpdateTime());
            inquiryPriceRecordPojo.setInquiryType(inquiryPricePojo.getInquiryType());
            inquiryPriceRecordPojo.setInquiryTypeDesc(InquiryTypeEnum.parse(inquiryPricePojo.getInquiryType()).getDesc());
            inquiryPriceRecordPojo.setInvoiceName(inquiryPricePojo.getInvoiceName());
            //如果两个报价都是null就不处理替换
            if (null != quotedPriceRecord){
                //用议价能修改的替换询价信息 目标价 议价数量 交货日期 有效期 报价
                inquiryPriceRecordPojo.setQuotedPrice(quotedPriceRecord.getQuotedPrice());
                inquiryPriceRecordPojo.setAmount(quotedPriceRecord.getAmount());
                inquiryPriceRecordPojo.setAcceptPrice(quotedPriceRecord.getAcceptPrice());
                inquiryPriceRecordPojo.setDeliveryDate(quotedPriceRecord.getDeliveryDate());
                inquiryPriceRecordPojo.setDeadline(quotedPriceRecord.getDeadline());
            }
            return inquiryPriceRecordPojo;
        }

        // 待询价 待报价 待询价 超时未报价 无法报价 都是按照询价记录一致
        BeanUtils.copyProperties(inquiryPriceRecordBO, inquiryPriceRecordPojo);
        inquiryPriceRecordPojo.setDeadline(inquiryPriceRecordBO.getRecordDeadline());
        inquiryPriceRecordPojo.setStatus(inquiryPriceRecordBO.getRecordStatus());
        inquiryPriceRecordPojo.setStatusDesc(InquiryPriceRecordStatusEnum.parse(inquiryPriceRecordBO.getRecordStatus()).getDesc());
        inquiryPriceRecordPojo.setNote(inquiryPriceRecordBO.getRecordNote());
        inquiryPriceRecordPojo.setCreateTime(inquiryPriceRecordBO.getRecordCreateTime());
        inquiryPriceRecordPojo.setUpdateTime(inquiryPriceRecordBO.getRecordUpdateTime());
        inquiryPriceRecordPojo.setInquiryType(inquiryPricePojo.getInquiryType());
        inquiryPriceRecordPojo.setInquiryTypeDesc(InquiryTypeEnum.parse(inquiryPricePojo.getInquiryType()).getDesc());
        inquiryPriceRecordPojo.setInvoiceName(inquiryPricePojo.getInvoiceName());
        return inquiryPriceRecordPojo;
    }

    /**
     * 获取询价详情
     *
     * @param id
     * @return
     */
    @Override
    public ServiceResult<InquiryPriceDetailsPojo> details(String id) {
        ServiceResult serviceResult = new ServiceResult<>();
        InquiryPriceDetailsPojo inquiryPriceDetailsPojo = new InquiryPriceDetailsPojo();
        //查询询价信息
        InquiryPriceRecord inquiryPriceRecord = inquiryPriceRecordMapper.selectById(id);
        if (null != inquiryPriceRecord) {
            InquiryPrice inquiryPrice = baseMapper.selectById(inquiryPriceRecord.getInquiryPriceId());
            if (null == inquiryPrice) {
                return null;
            }
            //封装询价
            inquiryPriceDetailsPojo.setInquiryPriceRecordPojo(inquiryPriceHandler.inquiryPriceRecordToInquiryPriceRecordPojo(inquiryPriceRecord, inquiryPrice.getInquiryType(), inquiryPrice.getInvoiceName()));
            //查询报价
            LambdaQueryWrapper<QuotedPriceRecord> quotedPriceRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
            quotedPriceRecordLambdaQueryWrapper.eq(QuotedPriceRecord::getRecordId, inquiryPriceRecord.getId());
            quotedPriceRecordLambdaQueryWrapper.eq(QuotedPriceRecord::getQuotedType, 1);
            quotedPriceRecordLambdaQueryWrapper.orderByDesc(QuotedPriceRecord::getCreateTime);
            quotedPriceRecordLambdaQueryWrapper.last("limit 1");
            QuotedPriceRecord quotedPriceRecord = quotedPriceRecordMapper.selectOne(quotedPriceRecordLambdaQueryWrapper);
            if (null != quotedPriceRecord) {
                //封装报价
                inquiryPriceDetailsPojo.setQuotedPriceRecordPojo(inquiryPriceHandler.quotedPriceRecordToQuotedPriceRecordPojo(quotedPriceRecord));
                //查询议价
                LambdaQueryWrapper<DiscussionPriceRecord> discussionPriceRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
                discussionPriceRecordLambdaQueryWrapper.eq(DiscussionPriceRecord::getQuotedPriceId, quotedPriceRecord.getId());
                //查询1:议价完成，2:议价中 3:议价失败的状态议价单
                discussionPriceRecordLambdaQueryWrapper.in(DiscussionPriceRecord::getStatus,
                        DiscussionPriceRecordStatusEnum.DISCUSSION_PRICE_COMPLETE.getStatus(),
                        DiscussionPriceRecordStatusEnum.DISCUSSION_PRICE_IN.getStatus(),
                        DiscussionPriceRecordStatusEnum.DISCUSSION_PRICE_FAIL.getStatus());
                discussionPriceRecordLambdaQueryWrapper.orderByDesc(DiscussionPriceRecord::getCreateTime);
                discussionPriceRecordLambdaQueryWrapper.last("limit 1");
                DiscussionPriceRecord discussionPriceRecord = discussionPriceRecordMapper.selectOne(discussionPriceRecordLambdaQueryWrapper);
                if (null != discussionPriceRecord) {
                    //封装议价
                    inquiryPriceDetailsPojo.setDiscussionPriceRecordPojo(inquiryPriceHandler.discussionPriceRecordToDiscussionPriceRecordPojo(discussionPriceRecord));
                    //查询报价
                    LambdaQueryWrapper<QuotedPriceRecord> quotedPriceRecordLambdaQueryWrapperTwo = new LambdaQueryWrapper<>();
                    quotedPriceRecordLambdaQueryWrapperTwo.eq(QuotedPriceRecord::getRecordId, inquiryPriceRecord.getId());
                    quotedPriceRecordLambdaQueryWrapperTwo.eq(QuotedPriceRecord::getQuotedType, 2);
                    quotedPriceRecordLambdaQueryWrapperTwo.orderByDesc(QuotedPriceRecord::getCreateTime);
                    quotedPriceRecordLambdaQueryWrapperTwo.last("limit 1");
                    QuotedPriceRecord quotedPriceRecordTwo = quotedPriceRecordMapper.selectOne(quotedPriceRecordLambdaQueryWrapperTwo);
                    if (null != quotedPriceRecordTwo) {
                        //封装报价
                        inquiryPriceDetailsPojo.setQuotedPriceRecordPojoTwo(inquiryPriceHandler.quotedPriceRecordToQuotedPriceRecordPojo(quotedPriceRecordTwo));
                    }
                }
            }
        }
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.OPERATE_SUCCESS);
        serviceResult.setResult(inquiryPriceDetailsPojo);
        return serviceResult;
    }

    /**
     * 返回当天所有询价单号
     *
     * @return
     */
    @Override
    public List<String> findAllSameDayNumber() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return baseMapper.findAllSameDayNumber(getStartOfDay(sdf, date), getEndOfDay(sdf, date));
    }

    /**
     * 发送询价
     *
     * @param ids
     * @param token
     */
    @Override
    public ServiceResult launchInquiry(List<String> ids, String token) {
        ServiceResult serviceResult = new ServiceResult<>();
        for (String id : ids) {
            pushErpInquiry(Integer.valueOf(id), token);
        }
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.OPERATE_SUCCESS);
        return serviceResult;
    }

    /**
     * 取消议价
     *
     * @param id    议价id
     * @param token
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, timeout = 30, rollbackFor = Exception.class)
    public ServiceResult cancelDiscussionPrice(Integer id, String token) {
        ServiceResult serviceResult = new ServiceResult<>();
        InquiryPriceRecord inquiryPriceRecord = inquiryPriceRecordMapper.selectById(id);
        if (null == inquiryPriceRecord) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("取消议价 : 失败 ,询价记录id:{" + id + "}未知");
            return serviceResult;
        }
        if (!inquiryPriceRecord.getStatus().equals(InquiryPriceRecordStatusEnum.DISCUSSION_PRICE_IN.getStatus())) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("取消议价 : 失败 ,询价记录状态不是议价中");
            return serviceResult;
        }
        //询价记录 只有1条数据是议价中
        LambdaQueryWrapper<DiscussionPriceRecord> discussionPriceRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        discussionPriceRecordLambdaQueryWrapper.eq(DiscussionPriceRecord::getInquiryPriceRecordId, inquiryPriceRecord.getId());
        discussionPriceRecordLambdaQueryWrapper.ne(DiscussionPriceRecord::getStatus, DiscussionPriceRecordStatusEnum.DISCUSSION_PRICE_IN.getDesc());
        discussionPriceRecordLambdaQueryWrapper.orderByDesc(DiscussionPriceRecord::getCreateTime);
        discussionPriceRecordLambdaQueryWrapper.last("limit 1");
        DiscussionPriceRecord discussionPriceRecord = discussionPriceRecordMapper.selectOne(discussionPriceRecordLambdaQueryWrapper);
        if (null == inquiryPriceRecord) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("取消议价 : 失败 ,询价记录id:{" + id + "}未知");
            return serviceResult;
        }
        //todo 调用erp 取消接口，根据返回状态更新对应状态

        //修改取消议价
        discussionPriceRecord.setStatus(DiscussionPriceRecordStatusEnum.CANCEL_DISCUSSION_PRICE.getStatus());
        int i = discussionPriceRecordMapper.updateById(discussionPriceRecord);
        if (i == 0) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("取消议价,失败");
            return serviceResult;
        }
        //修改其他记录状态
        //查询报价
        LambdaQueryWrapper<QuotedPriceRecord> quotedPriceRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        quotedPriceRecordLambdaQueryWrapper.eq(QuotedPriceRecord::getRecordId, inquiryPriceRecord.getId());
        quotedPriceRecordLambdaQueryWrapper.eq(QuotedPriceRecord::getQuotedType, 1);
        quotedPriceRecordLambdaQueryWrapper.orderByDesc(QuotedPriceRecord::getCreateTime);
        quotedPriceRecordLambdaQueryWrapper.last("limit 1");
        QuotedPriceRecord quotedPriceRecord = quotedPriceRecordMapper.selectOne(quotedPriceRecordLambdaQueryWrapper);
        if (null != quotedPriceRecord) {
            //判断date操作时间在报价截止之前 需要更改询价单和报价单状态为 已报价
            if (new Date().compareTo(quotedPriceRecord.getDeadline()) < 0) {
                inquiryPriceRecord.setStatus(InquiryPriceRecordStatusEnum.QUOTED.getStatus());
            } else {
                //判断date操作时间在报价截止之后或相等 需要更改询价单状态为 无效报价
                inquiryPriceRecord.setStatus(InquiryPriceRecordStatusEnum.INVALID_QUOTE.getStatus());
            }
            inquiryPriceRecordMapper.updateById(inquiryPriceRecord);
        }
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.OPERATE_SUCCESS);
        return serviceResult;
    }


    /**
     * 延时询价
     *
     * @param inquiryPriceDelayedVo
     * @param token
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, timeout = 30, rollbackFor = Exception.class)
    public ServiceResult delayedInquiryPrice(InquiryPriceDelayedVo inquiryPriceDelayedVo, String token) {
        ServiceResult serviceResult = new ServiceResult<>();
        InquiryPrice inquiryPrice = baseMapper.selectById(inquiryPriceDelayedVo.getId());
        if (null == inquiryPrice) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("延时询价 : 失败,id:{" + inquiryPriceDelayedVo.getId() + "未知");
            return serviceResult;
        }
        LambdaQueryWrapper<InquiryPriceRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(InquiryPriceRecord::getInquiryPriceId, inquiryPrice.getId());
        wrapper.eq(InquiryPriceRecord::getStatus, InquiryPriceRecordStatusEnum.NO_QUOTATION_OVERTIME.getStatus());
        List<InquiryPriceRecord> inquiryPriceRecordList = inquiryPriceRecordMapper.selectList(wrapper);
        //询价延迟消息
        List<InquiryDelayMqMessagePojo> inquiryDelayMqMessagePojoList = new ArrayList<>();
        for (InquiryPriceRecord inquiryPriceRecord : inquiryPriceRecordList) {
            inquiryPriceRecord.setDeadline(inquiryPriceDelayedVo.getDeadline());
            inquiryPriceRecord.setStatus(InquiryPriceRecordStatusEnum.TO_BE_QUOTATION.getStatus());
            inquiryPriceRecordMapper.updateById(inquiryPriceRecord);
            //封装处理延迟消息实体
            InquiryDelayMqMessagePojo inquiryDelayMqMessagePojo = new InquiryDelayMqMessagePojo();
            inquiryDelayMqMessagePojo.setId(inquiryPriceRecord.getId());
            inquiryDelayMqMessagePojo.setCurrentState(InquiryPriceRecordStatusEnum.TO_BE_QUOTATION.getStatus());
            inquiryDelayMqMessagePojo.setDeadline(inquiryPriceRecord.getDeadline());
            inquiryDelayMqMessagePojoList.add(inquiryDelayMqMessagePojo);
        }

        //修改询价单有效时间
        inquiryPrice.setDeadline(inquiryPriceDelayedVo.getDeadline());
        baseMapper.updateById(inquiryPrice);

        //发送消息
        try {
            sendMsg(inquiryDelayMqMessagePojoList);
        } catch (IOException e) {
            log.info("延时询价 : inquiryDelayMqMessagePojoList:{},发送消息异常", JSON.toJSONString(inquiryDelayMqMessagePojoList));
        }
        //todo 向erp发送延时有效时间

        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.OPERATE_SUCCESS);
        return serviceResult;
    }

    /**
     * 议价
     *
     * @param discussionPriceCreatedVo
     * @param token
     * @return
     */
    @Override
    public ServiceResult discussionPrice(DiscussionPriceCreatedVo discussionPriceCreatedVo, String token) {
        ServiceResult serviceResult = new ServiceResult<>();

        InquiryPriceRecord inquiryPriceRecord = inquiryPriceRecordMapper.selectById(discussionPriceCreatedVo.getInquiryPriceId());
        if (null == inquiryPriceRecord) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("议价 : 失败,询价记录id:{" + discussionPriceCreatedVo.getInquiryPriceId() + "未知");
            return serviceResult;
        }
        //查询报价
        LambdaQueryWrapper<QuotedPriceRecord> quotedPriceRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        quotedPriceRecordLambdaQueryWrapper.eq(QuotedPriceRecord::getRecordId, inquiryPriceRecord.getId());
        quotedPriceRecordLambdaQueryWrapper.eq(QuotedPriceRecord::getQuotedType, 1);
        quotedPriceRecordLambdaQueryWrapper.orderByDesc(QuotedPriceRecord::getCreateTime);
        quotedPriceRecordLambdaQueryWrapper.last("limit 1");
        QuotedPriceRecord quotedPriceRecord = quotedPriceRecordMapper.selectOne(quotedPriceRecordLambdaQueryWrapper);
        if (null == quotedPriceRecord) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("议价 : 失败,询价记录id:{" + discussionPriceCreatedVo.getInquiryPriceId() + "未知");
            return serviceResult;
        }

        //1.先查询是否有创建但是没有发送给erp的 有就更新 没有就创建
        LambdaQueryWrapper<DiscussionPriceRecord> discussionPriceRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        discussionPriceRecordLambdaQueryWrapper.eq(DiscussionPriceRecord::getInquiryPriceRecordId, inquiryPriceRecord.getId());
        discussionPriceRecordLambdaQueryWrapper.eq(DiscussionPriceRecord::getQuotedPriceId, quotedPriceRecord.getId());
        discussionPriceRecordLambdaQueryWrapper.eq(DiscussionPriceRecord::getStatus, DiscussionPriceRecordStatusEnum.DISCUSSION_PRICE_INIT.getStatus());
        discussionPriceRecordLambdaQueryWrapper.orderByDesc(DiscussionPriceRecord::getCreateTime);
        discussionPriceRecordLambdaQueryWrapper.last("limit 1");
        DiscussionPriceRecord discussionPriceRecord = discussionPriceRecordMapper.selectOne(discussionPriceRecordLambdaQueryWrapper);
        Date date = new Date();
        //没有就创建
        if (null == discussionPriceRecord) {
            discussionPriceRecord = new DiscussionPriceRecord();
            discussionPriceRecord.setQuotedPriceId(quotedPriceRecord.getId());
            discussionPriceRecord.setInquiryPriceId(inquiryPriceRecord.getInquiryPriceId());
            discussionPriceRecord.setInquiryPriceRecordId(inquiryPriceRecord.getId());
            discussionPriceRecord.setModel(inquiryPriceRecord.getModel());
            discussionPriceRecord.setBrand(inquiryPriceRecord.getBrand());
            discussionPriceRecord.setAmount(discussionPriceCreatedVo.getAmount());
            discussionPriceRecord.setBatch(inquiryPriceRecord.getBatch());
            discussionPriceRecord.setEncapsulation(inquiryPriceRecord.getEncapsulation());
            discussionPriceRecord.setAcceptPrice(discussionPriceCreatedVo.getAcceptPrice());
            discussionPriceRecord.setDeliveryDate(discussionPriceCreatedVo.getDeliveryDate());
            discussionPriceRecord.setDeadline(discussionPriceCreatedVo.getDeadline());
            discussionPriceRecord.setMpq(inquiryPriceRecord.getMpq());
            discussionPriceRecord.setPacking(inquiryPriceRecord.getPacking());
            discussionPriceRecord.setStatus(DiscussionPriceRecordStatusEnum.DISCUSSION_PRICE_INIT.getStatus());
            discussionPriceRecord.setNote(discussionPriceCreatedVo.getNote());
            discussionPriceRecord.setCurrency(quotedPriceRecord.getCurrency());
            discussionPriceRecord.setDeliveryPlace(quotedPriceRecord.getDeliveryPlace());
            discussionPriceRecord.setCreateTime(date);
            discussionPriceRecord.setUpdateTime(date);
            discussionPriceRecordMapper.insert(discussionPriceRecord);
        } else {
            discussionPriceRecord.setAmount(discussionPriceCreatedVo.getAmount());
            discussionPriceRecord.setAcceptPrice(discussionPriceCreatedVo.getAcceptPrice());
            discussionPriceRecord.setDeliveryDate(discussionPriceCreatedVo.getDeliveryDate());
            discussionPriceRecord.setDeadline(discussionPriceCreatedVo.getDeadline());
            discussionPriceRecord.setNote(discussionPriceCreatedVo.getNote());
            discussionPriceRecordMapper.updateById(discussionPriceRecord);
        }

        //todo 2.发送议价信息给erp
        //3 根据erp返回的信息 更新议价信息 主要更新状态为 报价中 并记录erp返回的议价单号

        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.OPERATE_SUCCESS);
        return serviceResult;
    }

    /**
     * 处理延迟消息 修改状态
     *
     * @param msg
     */
    @Override
    public void handleMsg(String msg) {
        InquiryDelayMqMessagePojo inquiryDelayMqMessagePojo = JSON.parseObject(msg, InquiryDelayMqMessagePojo.class);
        //忽略错误信息
        if (null == inquiryDelayMqMessagePojo) {
            return;
        }
        //查询需要更改状态的记录
        InquiryPriceRecord inquiryPriceRecord = inquiryPriceRecordMapper.selectById(inquiryDelayMqMessagePojo.getId());
        if (null == inquiryPriceRecord) {
            log.warn("处理延迟消息 修改状态,消息异常,询价记录未知,inquiryDelayMqMessagePojo:{}", JSON.toJSONString(inquiryDelayMqMessagePojo));
            return;
        }
        //查询询价单
        InquiryPrice inquiryPrice = baseMapper.selectById(inquiryPriceRecord.getInquiryPriceId());
        if (null == inquiryPrice) {
            log.warn("处理延迟消息 修改状态,消息异常,询价记录未知,inquiryDelayMqMessagePojo:{}", JSON.toJSONString(inquiryDelayMqMessagePojo));
            return;
        }
        //判断询价记录单的状态 是否和预期状态一致,如果一致在执行修改
        if (inquiryPriceRecord.getStatus().equals(inquiryDelayMqMessagePojo.getCurrentState())) {
            //待报价 如果过期需要查询 erp的表看看是不是无法报价状态，不是无法报价 ，就当超时未报价处理
            if (inquiryDelayMqMessagePojo.getCurrentState().equals(InquiryPriceRecordStatusEnum.TO_BE_QUOTATION.getStatus())) {
                //todo 查询报价状态
                inquiryPriceRecord.setStatus(InquiryPriceRecordStatusEnum.NO_QUOTATION_OVERTIME.getStatus());
                inquiryPriceRecordMapper.updateById(inquiryPriceRecord);
                //bom需要更改
                if (inquiryPrice.getInquiryMethod().equals(InquiryMethodEnum.BOM_INQUIRY.getType())) {
                    checkInquiryPriceStatusAndUpdateStatus(inquiryPrice);
                }
                return;
            }
            //已报价 过期需要更改为 无效报价
            if (inquiryDelayMqMessagePojo.getCurrentState().equals(InquiryPriceRecordStatusEnum.QUOTED.getStatus())) {
                inquiryPriceRecord.setStatus(InquiryPriceRecordStatusEnum.INVALID_QUOTE.getStatus());
                inquiryPriceRecordMapper.updateById(inquiryPriceRecord);
                LambdaQueryWrapper<QuotedPriceRecord> quotedPriceRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
                quotedPriceRecordLambdaQueryWrapper.eq(QuotedPriceRecord::getRecordId, inquiryPriceRecord.getId());
                quotedPriceRecordLambdaQueryWrapper.eq(QuotedPriceRecord::getQuotedType, 1);
                quotedPriceRecordLambdaQueryWrapper.orderByDesc(QuotedPriceRecord::getCreateTime);
                quotedPriceRecordLambdaQueryWrapper.last("limit 1");
                QuotedPriceRecord quotedPriceRecord = quotedPriceRecordMapper.selectOne(quotedPriceRecordLambdaQueryWrapper);
                if (null != quotedPriceRecord) {
                    quotedPriceRecord.setStatus(QuotedPriceRecordStatusEnum.INVALID_QUOTE.getStatus());
                    quotedPriceRecordMapper.updateById(quotedPriceRecord);
                } else {
                    log.warn("处理延迟消息 修改状态,未找到对应的报价记录,inquiryDelayMqMessagePojo:{}", JSON.toJSONString(inquiryDelayMqMessagePojo));
                }
                //bom需要更改
                if (inquiryPrice.getInquiryMethod().equals(InquiryMethodEnum.BOM_INQUIRY.getType())) {
                    checkInquiryPriceStatusAndUpdateStatus(inquiryPrice);
                }
                return;
            }
            //议价中 过期需要更改为 议价失败
            if (inquiryDelayMqMessagePojo.getCurrentState().equals(InquiryPriceRecordStatusEnum.DISCUSSION_PRICE_IN.getStatus())) {


                LambdaQueryWrapper<QuotedPriceRecord> quotedPriceRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
                quotedPriceRecordLambdaQueryWrapper.eq(QuotedPriceRecord::getRecordId, inquiryPriceRecord.getId());
                quotedPriceRecordLambdaQueryWrapper.eq(QuotedPriceRecord::getQuotedType, 1);
                quotedPriceRecordLambdaQueryWrapper.orderByDesc(QuotedPriceRecord::getCreateTime);
                quotedPriceRecordLambdaQueryWrapper.last("limit 1");
                QuotedPriceRecord quotedPriceRecord = quotedPriceRecordMapper.selectOne(quotedPriceRecordLambdaQueryWrapper);
                if (null != quotedPriceRecord) {
                    LambdaQueryWrapper<DiscussionPriceRecord> discussionPriceRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    discussionPriceRecordLambdaQueryWrapper.eq(DiscussionPriceRecord::getInquiryPriceRecordId, inquiryPriceRecord.getId());
                    discussionPriceRecordLambdaQueryWrapper.eq(DiscussionPriceRecord::getQuotedPriceId, quotedPriceRecord.getId());
                    discussionPriceRecordLambdaQueryWrapper.eq(DiscussionPriceRecord::getStatus, DiscussionPriceRecordStatusEnum.DISCUSSION_PRICE_IN.getStatus());
                    discussionPriceRecordLambdaQueryWrapper.orderByDesc(DiscussionPriceRecord::getCreateTime);
                    discussionPriceRecordLambdaQueryWrapper.last("limit 1");
                    DiscussionPriceRecord discussionPriceRecord = discussionPriceRecordMapper.selectOne(discussionPriceRecordLambdaQueryWrapper);
                    if (null != discussionPriceRecord) {
                        //判断date操作时间在报价截止之前 是议价完成
                        if (new Date().compareTo(quotedPriceRecord.getDeadline()) < 0) {
                            inquiryPriceRecord.setStatus(InquiryPriceRecordStatusEnum.DISCUSSION_PRICE_COMPLETE.getStatus());
                            discussionPriceRecord.setStatus(DiscussionPriceRecordStatusEnum.DISCUSSION_PRICE_COMPLETE.getStatus());
                            QuotedPriceRecord quotedPriceRecord1 = new QuotedPriceRecord();
                            BeanUtils.copyProperties(quotedPriceRecord, quotedPriceRecord1);
                            quotedPriceRecord1.setId(null);
                            quotedPriceRecord1.setRecordId(discussionPriceRecord.getId());
                            quotedPriceRecord1.setQuotedType(2);
                            quotedPriceRecord1.setStatus(QuotedPriceRecordStatusEnum.DISCUSSION_PRICE_COMPLETE.getStatus());
                            quotedPriceRecordMapper.insert(quotedPriceRecord1);
                        } else {
                            //判断date操作时间在报价截止之后或相等 需要更改询价单状态为 议价失败
                            inquiryPriceRecord.setStatus(InquiryPriceRecordStatusEnum.DISCUSSION_PRICE_FAIL.getStatus());
                            discussionPriceRecord.setStatus(DiscussionPriceRecordStatusEnum.DISCUSSION_PRICE_FAIL.getStatus());
                        }
                        inquiryPriceRecordMapper.updateById(inquiryPriceRecord);
                        discussionPriceRecordMapper.updateById(discussionPriceRecord);
                    } else {
                        log.warn("处理延迟消息 修改状态,未找到对应的议价记录,inquiryDelayMqMessagePojo:{}", JSON.toJSONString(inquiryDelayMqMessagePojo));
                    }
                } else {
                    log.warn("处理延迟消息 修改状态,未找到对应的报价记录,inquiryDelayMqMessagePojo:{}", JSON.toJSONString(inquiryDelayMqMessagePojo));
                }
                //bom需要更改
                if (inquiryPrice.getInquiryMethod().equals(InquiryMethodEnum.BOM_INQUIRY.getType())) {
                    checkInquiryPriceStatusAndUpdateStatus(inquiryPrice);
                }
                return;
            }
            //议价完成 过期需要更改为 议价失败
            if (inquiryDelayMqMessagePojo.getCurrentState().equals(InquiryPriceRecordStatusEnum.DISCUSSION_PRICE_IN.getStatus())) {
                inquiryPriceRecord.setStatus(InquiryPriceRecordStatusEnum.DISCUSSION_PRICE_FAIL.getStatus());
                inquiryPriceRecordMapper.updateById(inquiryPriceRecord);
                LambdaQueryWrapper<QuotedPriceRecord> quotedPriceRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
                quotedPriceRecordLambdaQueryWrapper.eq(QuotedPriceRecord::getRecordId, inquiryPriceRecord.getId());
                quotedPriceRecordLambdaQueryWrapper.eq(QuotedPriceRecord::getQuotedType, 1);
                quotedPriceRecordLambdaQueryWrapper.orderByDesc(QuotedPriceRecord::getCreateTime);
                quotedPriceRecordLambdaQueryWrapper.last("limit 1");
                QuotedPriceRecord quotedPriceRecord = quotedPriceRecordMapper.selectOne(quotedPriceRecordLambdaQueryWrapper);
                if (null != quotedPriceRecord) {
                    LambdaQueryWrapper<DiscussionPriceRecord> discussionPriceRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    discussionPriceRecordLambdaQueryWrapper.eq(DiscussionPriceRecord::getInquiryPriceRecordId, inquiryPriceRecord.getId());
                    discussionPriceRecordLambdaQueryWrapper.eq(DiscussionPriceRecord::getQuotedPriceId, quotedPriceRecord.getId());
                    discussionPriceRecordLambdaQueryWrapper.eq(DiscussionPriceRecord::getStatus, DiscussionPriceRecordStatusEnum.DISCUSSION_PRICE_IN.getStatus());
                    discussionPriceRecordLambdaQueryWrapper.orderByDesc(DiscussionPriceRecord::getCreateTime);
                    discussionPriceRecordLambdaQueryWrapper.last("limit 1");
                    DiscussionPriceRecord discussionPriceRecord = discussionPriceRecordMapper.selectOne(discussionPriceRecordLambdaQueryWrapper);
                    if (null != discussionPriceRecord) {
                        discussionPriceRecord.setStatus(DiscussionPriceRecordStatusEnum.DISCUSSION_PRICE_FAIL.getStatus());
                        discussionPriceRecordMapper.updateById(discussionPriceRecord);
                    } else {
                        log.warn("处理延迟消息 修改状态,未找到对应的议价记录,inquiryDelayMqMessagePojo:{}", JSON.toJSONString(inquiryDelayMqMessagePojo));
                    }
                } else {
                    log.warn("处理延迟消息 修改状态,未找到对应的报价记录,inquiryDelayMqMessagePojo:{}", JSON.toJSONString(inquiryDelayMqMessagePojo));
                }
                //bom需要更改
                if (inquiryPrice.getInquiryMethod().equals(InquiryMethodEnum.BOM_INQUIRY.getType())) {
                    checkInquiryPriceStatusAndUpdateStatus(inquiryPrice);
                }
                return;
            }
        }
    }


    /**
     * todo 推送erp询价
     *
     * @param id
     * @return
     */
    private void pushErpInquiry(Integer id, String token) {
        try {
            InquiryPrice inquiryPrice = baseMapper.selectById(id);
            if (null == inquiryPrice) {
                return;
            }
            LambdaQueryWrapper<InquiryPriceRecord> wrapper = new LambdaQueryWrapper();
            wrapper.eq(InquiryPriceRecord::getInquiryPriceId, id);
            List<InquiryPriceRecord> inquiryPriceRecordList = inquiryPriceRecordMapper.selectList(wrapper);
            if (CollectionUtils.isEmpty(inquiryPriceRecordList)) {
                return;
            }
            ErpPushInquiryPriceRequest erpPushInquiryPriceRequest = new ErpPushInquiryPriceRequest();

            erpPushInquiryPriceRequest.setClientID(inquiryPrice.getSiteId());
            //固定发货地 大陆
            erpPushInquiryPriceRequest.setDistrict("FArea01");
            erpPushInquiryPriceRequest.setSource(3);
            //币种
            erpPushInquiryPriceRequest.setCurrency(inquiryPrice.getCurrency().toString());
            erpPushInquiryPriceRequest.setInvoiceType(4);
            erpPushInquiryPriceRequest.setInvoiceMethod(1);
            //询价延迟消息
            List<InquiryDelayMqMessagePojo> inquiryDelayMqMessagePojoList = new ArrayList<>();
            List<ErpPushInquiryPriceRequest.Inquirys> list = inquiryPriceRecordList.stream().map(inquiryPriceRecord -> {
                //封装处理延迟消息实体
                InquiryDelayMqMessagePojo inquiryDelayMqMessagePojo = new InquiryDelayMqMessagePojo();
                inquiryDelayMqMessagePojo.setId(inquiryPriceRecord.getId());
                inquiryDelayMqMessagePojo.setCurrentState(InquiryPriceRecordStatusEnum.TO_BE_QUOTATION.getStatus());
                inquiryDelayMqMessagePojo.setDeadline(inquiryPriceRecord.getDeadline());
                inquiryDelayMqMessagePojoList.add(inquiryDelayMqMessagePojo);
                //处理推送信息
                ErpPushInquiryPriceRequest.Inquirys inquirys = new ErpPushInquiryPriceRequest.Inquirys();
                inquirys.setPartNumber(inquiryPriceRecord.getModel());
                inquirys.setBrand(inquiryPriceRecord.getBrand());

                inquirys.setQuantity(inquiryPriceRecord.getAmount());

                inquirys.setSalerID(inquiryPrice.getSalerId());
                //交货日期
                inquirys.setDeliveryDate(inquiryPriceRecord.getDeliveryDate().toString());
                //购货性质
                inquirys.setNature(1);
                //不走代理
                inquirys.setIsAgent(false);
                //询价类型为1
                inquirys.setInquiryOrderType(1);
                return inquirys;
            }).collect(Collectors.toList());
            erpPushInquiryPriceRequest.setInquirys(list);
            //todo 测试临时注释
            // ErpPushInquiryPriceResponse erpPushInquiryPriceResponse = erpHandler.pushInquiryPriceRequest(erpPushInquiryPriceRequest, token);
            //if (erpPushInquiryPriceResponse != null || erpPushInquiryPriceResponse.isSuccess()) {
            //1、发送询价成功后需要 更改待询价状态为待报价
            inquiryPriceRecordMapper.updateStatusByInquiryPriceId(id, InquiryPriceRecordStatusEnum.PENDING.getStatus(), InquiryPriceRecordStatusEnum.TO_BE_QUOTATION.getStatus());
            //2、成功后需要放入mq延迟队列
            sendMsg(inquiryDelayMqMessagePojoList);
            // }
        } catch (Exception e) {
            log.info("推送推送erp询价 异常", e);
        }
    }

    /**
     * 发送消息
     *
     * @param inquiryDelayMqMessagePojoList
     * @throws IOException
     */
    private void sendMsg(List<InquiryDelayMqMessagePojo> inquiryDelayMqMessagePojoList) throws IOException {
        log.info("向延迟队列发送消息 开始");
        Date date = new Date();
        for (InquiryDelayMqMessagePojo inquiryDelayMqMessagePojo : inquiryDelayMqMessagePojoList) {
            String content = JSON.toJSONString(inquiryDelayMqMessagePojo);
            byte[] msg = content.getBytes(StandardCharsets.UTF_8);
            Map<String, Object> headers = new HashMap<>();
            headers.put("x-delay", inquiryDelayMqMessagePojo.getDeadline().getTime() - date.getTime());
            AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder().headers(headers).build();
            serviceHelper.getRabbitMqManager().basicPublishDelay(RabbitMqConstants.INQUIRY_DElAY_EXCHANGE, RabbitMqConstants.INQUIRY_DElAY_ROUTING_KEY, properties, msg);
        }
        log.info("向延迟队列发送消息 结束");
    }

    /**
     * 获取入参开始时间
     *
     * @param sdf
     * @param time
     * @return
     */
    public String getStartOfDay(SimpleDateFormat sdf, Date time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return sdf.format(calendar.getTime());
    }

    /**
     * 获取入参结束时间
     *
     * @param sdf
     * @param time
     * @return
     */
    public String getEndOfDay(SimpleDateFormat sdf, Date time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return sdf.format(calendar.getTime());
    }


    /**
     * 转换状态
     *
     * @param status
     * @return
     */
    public List<Integer> compareStatus(Integer status) {
        //状态
        ArrayList<Integer> statusList = new ArrayList<>();
        if (status.equals(InquiryPriceRecordCompareStatusEnum.ALL.getStatus())) {
            return statusList;
        }
        //转换状态 已报价 状态 包含 议价完成
        if (status.equals(InquiryPriceRecordCompareStatusEnum.QUOTED.getStatus())) {
            statusList.add(InquiryPriceRecordStatusEnum.QUOTED.getStatus());
            statusList.add(InquiryPriceRecordStatusEnum.DISCUSSION_PRICE_COMPLETE.getStatus());
            return statusList;
        }
        //无效询价  包含 无法报价 无效报价 议价失败
        if (status.equals(InquiryPriceRecordCompareStatusEnum.INVALID_INQUIRY.getStatus())) {
            statusList.add(InquiryPriceRecordStatusEnum.UNABLE_TO_QUOTE.getStatus());
            statusList.add(InquiryPriceRecordStatusEnum.INVALID_QUOTE.getStatus());
            statusList.add(InquiryPriceRecordStatusEnum.DISCUSSION_PRICE_FAIL.getStatus());
            return statusList;
        }

        //待询价
        if (status.equals(InquiryPriceRecordCompareStatusEnum.PENDING.getStatus())) {
            statusList.add(InquiryPriceRecordStatusEnum.PENDING.getStatus());
            return statusList;
        }

        //待报价
        if (status.equals(InquiryPriceRecordCompareStatusEnum.TO_BE_QUOTATION.getStatus())) {
            statusList.add(InquiryPriceRecordStatusEnum.TO_BE_QUOTATION.getStatus());
            return statusList;
        }

        //议价中
        if (status.equals(InquiryPriceRecordCompareStatusEnum.UNDER_NEGOTIATION.getStatus())) {
            statusList.add(InquiryPriceRecordStatusEnum.DISCUSSION_PRICE_IN.getStatus());
            return statusList;
        }

        //已生成订单
        if (status.equals(InquiryPriceRecordCompareStatusEnum.ORDER_GENERATED.getStatus())) {
            statusList.add(InquiryPriceRecordStatusEnum.ORDER_GENERATED.getStatus());
            return statusList;
        }

        //超时未报价
        if (status.equals(InquiryPriceRecordCompareStatusEnum.NO_QUOTATION_OVERTIME.getStatus())) {
            statusList.add(InquiryPriceRecordStatusEnum.NO_QUOTATION_OVERTIME.getStatus());
            return statusList;
        }

        return statusList;
    }

    /**
     * 检查询价单是否需要更改状态
     *
     * @param id
     */
    private void checkInquiryPriceStatusAndUpdateStatus(String id) {
        InquiryPrice inquiryPrice = baseMapper.selectById(id);
        //排除为空的
        if (inquiryPrice == null) {
            return;
        }
        checkInquiryPriceStatusAndUpdateStatus(inquiryPrice);
    }

    /**
     * 检查询价单是否需要更改状态
     *
     * @param inquiryPrice
     */
    private void checkInquiryPriceStatusAndUpdateStatus(InquiryPrice inquiryPrice) {
        //查询所有品牌型号总数
        LambdaQueryWrapper<InquiryPriceRecord> countWrapper = new LambdaQueryWrapper<>();
        countWrapper.eq(InquiryPriceRecord::getInquiryPriceId, inquiryPrice.getId());
        Integer count = inquiryPriceRecordMapper.selectCount(countWrapper);

        InquiryPrice updateStatusInquiryPrice = new InquiryPrice();
        updateStatusInquiryPrice.setId(inquiryPrice.getId());
        //是否为待询价
        if (isPending(inquiryPrice.getId().toString(), count) && inquiryPrice.getStatus() != InquiryPriceStatusEnum.TO_BE_INQUIRED.getStatus()) {
            updateStatusInquiryPrice.setStatus(InquiryPriceStatusEnum.TO_BE_INQUIRED.getStatus());
            baseMapper.updateById(updateStatusInquiryPrice);
            return;
        }

        //是否为超时未报价
        if (isNoQuotationForOvertime(inquiryPrice.getId().toString(), count) && inquiryPrice.getStatus() != InquiryPriceStatusEnum.NO_QUOTATION_FOR_OVERTIME.getStatus()) {
            updateStatusInquiryPrice.setStatus(InquiryPriceStatusEnum.NO_QUOTATION_FOR_OVERTIME.getStatus());
            baseMapper.updateById(updateStatusInquiryPrice);
            return;
        }

        //是否为待报价
        if (isInQuotation(inquiryPrice.getId().toString(), count) && inquiryPrice.getStatus() != InquiryPriceStatusEnum.TO_BE_QUOTED.getStatus()) {
            updateStatusInquiryPrice.setStatus(InquiryPriceStatusEnum.TO_BE_QUOTED.getStatus());
            baseMapper.updateById(updateStatusInquiryPrice);
            return;
        }
        //是否无效询价
        if (isInvalidInquiry(inquiryPrice.getId().toString(), count) && inquiryPrice.getStatus() != InquiryPriceStatusEnum.INVALID_INQUIRY.getStatus()) {
            updateStatusInquiryPrice.setStatus(InquiryPriceStatusEnum.INVALID_INQUIRY.getStatus());
            baseMapper.updateById(updateStatusInquiryPrice);
            return;
        }

        //是否为已报价
        if (isQuotationCompleted(inquiryPrice.getId().toString(), count) && inquiryPrice.getStatus() != InquiryPriceStatusEnum.QUOTATION_COMPLETED.getStatus()) {
            updateStatusInquiryPrice.setStatus(InquiryPriceStatusEnum.QUOTATION_COMPLETED.getStatus());
            baseMapper.updateById(updateStatusInquiryPrice);
            return;
        }

        //是否为部分报价
        if (isPartialOffer(inquiryPrice.getId().toString(), count) && inquiryPrice.getStatus() != InquiryPriceStatusEnum.PARTIAL_OFFER.getStatus()) {
            updateStatusInquiryPrice.setStatus(InquiryPriceStatusEnum.PARTIAL_OFFER.getStatus());
            baseMapper.updateById(updateStatusInquiryPrice);
            return;
        }
    }


    /**
     * 是否为待询价
     *
     * @param id
     * @param count
     * @return
     */
    private Boolean isPending(String id, Integer count) {
        LambdaQueryWrapper<InquiryPriceRecord> invalidQuotationWrapper = new LambdaQueryWrapper<>();
        invalidQuotationWrapper.eq(InquiryPriceRecord::getInquiryPriceId, id);
        invalidQuotationWrapper.eq(InquiryPriceRecord::getStatus, InquiryPriceRecordStatusEnum.PENDING.getStatus());
        Integer pendingCount = inquiryPriceRecordMapper.selectCount(invalidQuotationWrapper);
        if (pendingCount.equals(count)) {
            return true;
        }
        return false;
    }


    /**
     * 是否为待报价
     *
     * @param id
     * @param count
     * @return
     */
    private Boolean isInQuotation(String id, Integer count) {
        LambdaQueryWrapper<InquiryPriceRecord> invalidQuotationWrapper = new LambdaQueryWrapper<>();
        invalidQuotationWrapper.eq(InquiryPriceRecord::getInquiryPriceId, id);
        invalidQuotationWrapper.eq(InquiryPriceRecord::getStatus, InquiryPriceRecordStatusEnum.TO_BE_QUOTATION.getStatus());
        Integer inQuotationCount = inquiryPriceRecordMapper.selectCount(invalidQuotationWrapper);
        if (inQuotationCount.equals(count)) {
            return true;
        }
        return false;
    }


    /**
     * 是否为超时未报价
     *
     * @param id
     * @param count
     * @return
     */
    private Boolean isNoQuotationForOvertime(String id, Integer count) {
        LambdaQueryWrapper<InquiryPriceRecord> inquiryPriceRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        inquiryPriceRecordLambdaQueryWrapper.eq(InquiryPriceRecord::getInquiryPriceId, id);
        inquiryPriceRecordLambdaQueryWrapper.eq(InquiryPriceRecord::getStatus, InquiryPriceRecordStatusEnum.NO_QUOTATION_OVERTIME.getStatus());
        Integer noQuotationForOvertimeCount = inquiryPriceRecordMapper.selectCount(inquiryPriceRecordLambdaQueryWrapper);
        if (noQuotationForOvertimeCount.equals(count)) {
            return true;
        }
        return false;
    }

    /**
     * 是否为无效询价
     *
     * @param id
     * @param count
     * @return
     */
    private boolean isInvalidInquiry(String id, Integer count) {
        LambdaQueryWrapper<InquiryPriceRecord> invalidQuotationWrapper = new LambdaQueryWrapper<>();
        invalidQuotationWrapper.eq(InquiryPriceRecord::getInquiryPriceId, id);
        invalidQuotationWrapper.in(InquiryPriceRecord::getStatus,
                InquiryPriceRecordStatusEnum.DISCUSSION_PRICE_FAIL.getStatus(),
                InquiryPriceRecordStatusEnum.UNABLE_TO_QUOTE.getStatus(),
                InquiryPriceRecordStatusEnum.INVALID_QUOTE.getStatus());
        Integer invalidQuotationCount = inquiryPriceRecordMapper.selectCount(invalidQuotationWrapper);
        if (invalidQuotationCount > 0 && invalidQuotationCount < count) {
            return true;
        }
        return false;
    }

    /**
     * 是否为已报价
     *
     * @param id
     * @param count
     * @return
     */
    private Boolean isQuotationCompleted(String id, Integer count) {
        LambdaQueryWrapper<InquiryPriceRecord> invalidQuotationWrapper = new LambdaQueryWrapper<>();
        invalidQuotationWrapper.eq(InquiryPriceRecord::getInquiryPriceId, id);
        invalidQuotationWrapper.in(InquiryPriceRecord::getStatus,
                InquiryPriceRecordStatusEnum.QUOTED.getStatus(),
                InquiryPriceRecordStatusEnum.DISCUSSION_PRICE_IN.getStatus(),
                InquiryPriceRecordStatusEnum.DISCUSSION_PRICE_COMPLETE.getStatus(),
                InquiryPriceRecordStatusEnum.ORDER_GENERATED.getStatus(),
                InquiryPriceRecordStatusEnum.DISCUSSION_PRICE_FAIL.getStatus(),
                InquiryPriceRecordStatusEnum.NO_QUOTATION_OVERTIME.getStatus(),
                InquiryPriceRecordStatusEnum.UNABLE_TO_QUOTE.getStatus(),
                InquiryPriceRecordStatusEnum.INVALID_QUOTE.getStatus());
        Integer quotationCompletedCount = inquiryPriceRecordMapper.selectCount(invalidQuotationWrapper);
        if (quotationCompletedCount.equals(count)) {
            return true;
        }
        return false;
    }

    /**
     * 是否为部分报价
     *
     * @param id
     * @return
     */
    private Boolean isPartialOffer(String id, Integer count) {
        LambdaQueryWrapper<InquiryPriceRecord> invalidQuotationWrapper = new LambdaQueryWrapper<>();
        invalidQuotationWrapper.eq(InquiryPriceRecord::getInquiryPriceId, id);
        invalidQuotationWrapper.in(InquiryPriceRecord::getStatus,
                InquiryPriceRecordStatusEnum.TO_BE_QUOTATION.getStatus(),
                InquiryPriceRecordStatusEnum.QUOTED.getStatus(),
                InquiryPriceRecordStatusEnum.DISCUSSION_PRICE_IN.getStatus(),
                InquiryPriceRecordStatusEnum.DISCUSSION_PRICE_COMPLETE.getStatus(),
                InquiryPriceRecordStatusEnum.ORDER_GENERATED.getStatus(),
                InquiryPriceRecordStatusEnum.DISCUSSION_PRICE_FAIL.getStatus(),
                InquiryPriceRecordStatusEnum.NO_QUOTATION_OVERTIME.getStatus(),
                InquiryPriceRecordStatusEnum.UNABLE_TO_QUOTE.getStatus(),
                InquiryPriceRecordStatusEnum.INVALID_QUOTE.getStatus());
        Integer invalidQuotationCount = inquiryPriceRecordMapper.selectCount(invalidQuotationWrapper);
        if (invalidQuotationCount > 0 && invalidQuotationCount < count) {
            return true;
        }
        return false;
    }


}
